package oauthprovider

import (
	"context"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/setting/model"
	"mall/service/setting/rpc/internal/svc"
	"mall/service/setting/rpc/internal/utils/errorhandler"
	"mall/service/setting/rpc/types/setting"

	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateOauthProviderLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateOauthProviderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateOauthProviderLogic {
	return &BackendUpdateOauthProviderLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// group: oauthprovider
func (l *BackendUpdateOauthProviderLogic) BackendUpdateOauthProvider(in *setting.OauthProviderInfo) (*setting.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	id := *in.Id

	data, err := l.svcCtx.OauthProvider.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if in.Sort != nil {
		data.Sort = uint16(*in.Sort)
	}
	if in.Name != nil {
		data.Name = *in.Name

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysOauthProviderColumns.Name] = map[string][]any{
			"equalTo": []any{*in.Name},
		}
		list, _, err := l.svcCtx.OauthProvider.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("setting.oauthProviderAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("setting.oauthProviderAlreadyExists")
		}
	}
	if in.ClientId != nil {
		data.ClientID = *in.ClientId
	}
	if in.ClientSecret != nil {
		data.ClientSecret = *in.ClientSecret
	}
	if in.RedirectUrl != nil {
		data.RedirectURL = *in.RedirectUrl
	}
	if in.Scopes != nil {
		data.Scopes = *in.Scopes
	}
	if in.AuthUrl != nil {
		data.AuthURL = *in.AuthUrl
	}
	if in.TokenUrl != nil {
		data.TokenURL = *in.TokenUrl
	}
	if in.AuthStyle != nil {
		data.AuthStyle = uint8(*in.AuthStyle)
	}
	if in.InfoUrl != nil {
		data.InfoURL = *in.InfoUrl
	}
	if in.Status != nil {
		data.Status = uint8(*in.Status)
	}
	data.UpdatedAt = time.Now()
	err = l.svcCtx.OauthProvider.Update(l.ctx, nil, data)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &setting.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
